package com.example.rdcproject.ving.notes.view.User;

import com.example.rdcproject.ving.notes.dao.UserDao;
import com.example.rdcproject.ving.notes.dao.WordBookDao;
import com.example.rdcproject.ving.notes.entity.User;
import com.example.rdcproject.ving.notes.entity.Word;
import com.example.rdcproject.ving.notes.service.ClockIn;
import com.example.rdcproject.ving.notes.service.ConnectionPool;
import com.example.rdcproject.ving.notes.service.TotalTime;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class LearnWordView extends JFrame {

    private List<Word> words;
    private int currentWordIndex ;
    private int currentIndex = 0;
   private  int count=0;
    private Word currentWord;



    private JLabel wordLabel;
    private JLabel meaningLabel;
    private JLabel timeLabel;
    private JButton knowButton;
    private JButton unknownButton;
    private JButton collectButton;

    //计时
    private long startTime;
    private long endTime;


    User user = User.getInstance();
    UserDao userDao = new UserDao();
    WordBookDao wordBookDao = new WordBookDao();
    ClockIn clockIn = new ClockIn();

    TotalTime time = new TotalTime();


    private  ConnectionPool connectionPool;
    private Connection connection;
    private Statement statement;

    public LearnWordView() {
        //从数据库获取单词
        loadWords();


        //配置一些组件
        initComponents();


        showWord();



    }

    //从数据库获取单词
    private void loadWords() {

        ConnectionPool connectionPool = null;
        Connection connection = null;
        PreparedStatement statement = null;

        try {
            connectionPool = ConnectionPool.getInstance();
            connection = connectionPool.getConnection();

            connection.setAutoCommit(false);

            words = new ArrayList<>();
            connection.commit();

            String sql = "select * from "+user.getNickname()+"wordbook";
            statement = connection.prepareStatement(sql);

            ResultSet rs =statement.executeQuery();
            while (rs.next()) {
                Word word = new Word();
                String wordEnglish = rs.getString("word");
                String meaning = rs.getString("meaning" );
                word.setWord(wordEnglish);
                word.setMeaning(meaning);
                words.add(word);
            }


            connection.commit();

            statement.close();
            connectionPool.releaseConnection(connection);

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,"请先添加词书");
        }

    }

    private void initComponents() {

        JPanel buttonPanel = new JPanel();

        // 创建单词显示标签和意思显示标签
        wordLabel = new JLabel();
        meaningLabel = new JLabel();
        timeLabel = new JLabel();

        // 创建按钮
        knowButton = new JButton("认识");
        unknownButton = new JButton("不认识");
        collectButton = new JButton("加入生词本");
        JButton nextButton = new JButton("下一个单词");

        // 将按钮添加到按钮面板上
        buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        buttonPanel.add(knowButton);
        buttonPanel.add(unknownButton);
        buttonPanel.add(collectButton);
        buttonPanel.add(nextButton);

        // 将单词标签、意思标签和按钮面板添加到主面板上
        setLayout(new BorderLayout());
        add(wordLabel, BorderLayout.NORTH);
        add(meaningLabel, BorderLayout.CENTER);
        add(timeLabel, BorderLayout.EAST);
        add(buttonPanel, BorderLayout.SOUTH);

        knowButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showNextWord();
            }
        });

        unknownButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                showMeaning();
            }
        });

        collectButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                addNewWordbook();
            }
        });

        nextButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showNextWord();
            }
        });

        startTime=System.currentTimeMillis();
        currentWordIndex = user.getCurrentWordIndex();
    }




    private void showNextWord() {


        // 获取当前单词在列表中的索引
        int currentIndex = words.indexOf(currentWord);

        if (currentIndex < words.size() - 1) {
            currentWordIndex = currentIndex + 1;
            count++;
            user.setWordCount(user.getWordCount() + 1);
            showWord();
        }else {
            showWord();
            JOptionPane.showMessageDialog(this, "已经是最后一个单词了！");

        }
    }


    private void showMeaning() {
        if (currentWord != null) {
            meaningLabel.setText(currentWord.getMeaning());
        }
    }

    private void addNewWordbook() {
        String word = wordLabel.getText();
        String meaning = meaningLabel.getText();


        try {
            connectionPool = ConnectionPool.getInstance();
            connection = connectionPool.getConnection();
            statement = connection.createStatement();

            // 检查该单词是否已存在于生词本中

            String createSql = "create table if not exists "+ user.getNickname()+"newbook (id int not NULL AUTO_INCREMENT , word VARCHAR(255), "
                    +" meaning VARCHAR(255),PRIMARY KEY ( id ))";
            statement.execute(createSql);

            String selectSql = "select * from "+user.getNickname()+"newbook where word='"+word+"'";
            statement =connection.prepareStatement(selectSql);

            ResultSet rs = statement.executeQuery(selectSql);
            if (rs.next()) {
                JOptionPane.showMessageDialog(this, "该单词已存在于生词本中");
                return;
            }

            // 将单词和意思添加到生词本中
            String addSql = "insert into "+user.getNickname()+"newbook (word, meaning) values ('"+word +"','" +meaning+"')";
            int rowsAffected = statement.executeUpdate(addSql);
            if (rowsAffected > 0) {
                JOptionPane.showMessageDialog(this, "已将该单词添加到生词本中");
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void showWord() {
        if (currentWordIndex >= words.size()||count==user.getDailyGoal()) {
            JOptionPane.showMessageDialog(this, "已经学完了今日份所有单词！");

            endTime =System.currentTimeMillis();

            time.saveTotalStudyTime((endTime-startTime)/1000/60);

            //自动完成打卡和更新数据
           clockIn.clockDates(user.getNickname());

            user.setCurrentWordIndex(currentWordIndex);
            userDao.updateWord(user);
            return;
        }

        currentWord = words.get(currentWordIndex);
        wordLabel.setText(currentWord.getWord());

        // 显示中文
        meaningLabel.setText(" ");


        // 重置按钮状态
        knowButton.setEnabled(true);
        unknownButton.setEnabled(true);
        collectButton.setEnabled(true);


    }

}
